package com.monster.starter.core.utils;

import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Io工具类
 *
 * @author kuang
 */
public class IoUtils extends IOUtils {
    /**
     * 创建ServletInputStream对象
     *
     * @param data 数据
     * @return ServletInputStream
     */
    public static ServletInputStream createServletInputStream(String data) {
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener listener) {
                throw new UnsupportedOperationException();
            }
            @Override
            public int read() throws IOException {
                return inputStream.read();
            }

            @Override
            public int read(byte[] b, int off, int len) throws IOException {
                return inputStream.read(b, off, len);
            }

            @Override
            public int read(byte[] b) throws IOException {
                return inputStream.read(b);
            }

            @Override
            public long skip(long n) throws IOException {
                return inputStream.skip(n);
            }

            @Override
            public int available() throws IOException {
                return inputStream.available();
            }

            @Override
            public void close() throws IOException {
                inputStream.close();
            }

            @Override
            public synchronized void mark(int readlimit) {
                inputStream.mark(readlimit);
            }

            @Override
            public synchronized void reset() throws IOException {
                inputStream.reset();
            }

            @Override
            public boolean markSupported() {
                return inputStream.markSupported();
            }
        };
    }
}
